package toolsdk

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"encoding/json"
	"errors"
)

/*
	微信业务数据解密算法
*/

type WxCrypt struct {
	AppId      string
	SessionKey string
	RespDto    interface{} // 自定义struct，用于接收解密的结果
}

// Decrypt 微信业务数据解密 AES-128-CBC
func (w *WxCrypt) Decrypt(encryptedData string, iv string) error {
	if len(w.SessionKey) != 24 {
		return errors.New("sessionKey字符串长度必须是24")
	}
	aesKey, err := base64.StdEncoding.DecodeString(w.SessionKey)
	if err != nil {
		return err
	}
	if len(iv) != 24 {
		return errors.New("iv字符串长度必须是24")
	}
	aesIV, err := base64.StdEncoding.DecodeString(iv)
	if err != nil {
		return err
	}
	aesCipher, err := base64.StdEncoding.DecodeString(encryptedData)
	if err != nil {
		return err
	}
	cipherBlock, err := aes.NewCipher(aesKey)
	if err != nil {
		return err
	}
	blockMode := cipher.NewCBCDecrypter(cipherBlock, aesIV)
	dst := make([]byte, len(aesCipher))
	blockMode.CryptBlocks(dst, aesCipher)
	res := w.PKCS7UnPadding(dst)
	err = json.Unmarshal(res, &w.RespDto)
	return err
}

func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func (w *WxCrypt) PKCS7UnPadding(src []byte) []byte {
	length := len(src)
	unpadding := int(src[length-1])
	if length-unpadding < 0 {
		return []byte("")
	}
	return src[:(length - unpadding)]
}
